import { listMyChartByPageUsingPost } from '@/services/znxs-bi/chartController';
import { history, useModel } from '@umijs/max';
import { Avatar, Card, Input, List, message, Result } from 'antd';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useState } from 'react';
const { Search } = Input;

const MyChart: React.FC = () => {
  // 初始化 搜索参数
  const initSearchParam = {
    name: '',
    current: 1,
    pageSize: 6,
    sortField: 'createTime',
    sortOrder: 'desc',
  };

  const { initialState } = useModel('@@initialState');
  // 获取当前登录用户
  const { currentUser } = initialState ?? {};
  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParam });
  const [chartList, setChartList] = useState<API.Chart[]>();
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState(false);

  // 获取分页数据

  const loadData = async () => {
    setLoading(true);
    const res = await listMyChartByPageUsingPost(searchParams);

    if (res.code === 200) {
      message.success('用户【' + currentUser?.userName + '】的图表数据获取成功');
      // 处理数据  统一处理标题
      res.data?.records?.forEach((item) => {
        if (item.status === 'succeed') {
          try {
            const temp = JSON.parse(item.genChart ?? '{}');
            temp.title = undefined;
            item.genChart = temp;
          } catch (error) {
            message.error('图表解析参数出错');
          }
        }
      });
    } else {
      message.error('获取数据失败，请联系管理员');
      history.push('./404.tsx');
    }
    setLoading(false);
    // 传入item
    setChartList(res.data?.records);
    setTotal(res.data?.total ?? 0);
  };

  useEffect(() => {
    loadData();
  }, [searchParams]);

  // 搜索
  const onSearch = (value: any) => {
    setSearchParams({ ...initSearchParam, name: value });
  };

  return (
    <div>
      <Search
        placeholder="根据名称进行搜索内容"
        enterButton="搜索"
        onSearch={onSearch}
        size="large"
        loading={loading}
      />
      ,
      <List
        grid={{
          gutter: 18,
          xs: 1,
          sm: 1,
          md: 1,
          lg: 2,
          xl: 2,
          xxl: 2,
        }}
        itemLayout="vertical"
        pagination={{
          total: total,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          // 点击改变页数时调用
          onChange: (page, pageSize) => {
            // 传入点击的页数
            setSearchParams({ ...initSearchParam, current: page, pageSize });
          },
        }}
        dataSource={chartList}
        loading={loading}
        renderItem={(item) => (
          <Card style={{ margin: '10px' }}>
            <List.Item
              key={item.id}
              extra={
                <>
                  {item.status === 'wait' ? <Result title="任务等待中" /> : ''}
                  {item.status === 'running' ? <Result title="ai 生成中" /> : ''}
                  {item.status === 'succeed' ? (
                    <>
                      <ReactECharts option={item.genChart ?? {}} />
                      <br />
                    </>
                  ) : (
                    ''
                  )}
                  {item.status === 'failed' ? (
                    <Result status="error" title="生成失败" subTitle={item.execMessage}></Result>
                  ) : (
                    ''
                  )}
                </>
              }
            >
              <List.Item.Meta
                avatar={<Avatar src={currentUser?.userAvatar} />}
                description={item.goal}
                title={item.name}
              />

              <div>{item.genResult}</div>
            </List.Item>
          </Card>
        )}
      />
    </div>
  );
};

export default MyChart;
